////////////////////////////////////////////////////////////////////////////////
//////// BUILDING REGRESSION OUTCOMES
////////////////////////////////////////////////////////////////////////////////

local outcomes_list = "growth_gdpc_penn inflation_imf unemployment_ilo trade_wb hdi democracy_index polyarchy liberal partip delib egal ex_respect_con ex_bribe ex_embez ex_cor_exch ex_theft burocrat_merit impartial_admin bureaucracy_index accountability veracc diagacc horacc corruption ex_corruption pub_corruption women_emp growth_gdpc_madd growth_gdp_madd log_gdp_madd log_gdpc_madd mid_level growth_gdp_penn growth_cons_penn growth_cap_penn growth_prod_penn log_gdp_penn log_gdpc_penn trade_intensity imports_cepii exports_cepii growth_gdp_wb growth_gdpc_wb inflation_cp_wb inflation_def_wb imports_wb exports_wb poverty_head_190 poverty_gap tax_revenue_wb share_tax_goods share_tax_income share_tax_trade gini_wb hospital_beds life_exp crime undernourishment control_corruption gov_effective reg_quality rule_law voice_account stability_viol log_gdp_wb log_gdpc_wb subsidies_transf infant_mr tariff_wb debt_imf hdi_without_income lifeexp_index educ_index income_index share_health_exp exp_mili_gdp exp_educ_gdp exp_health_gdp exp_gdp share_educ_exp share_mili_exp cbi_cwn interstate_war intrastate_war extrastate_war in_war polity_score xconst polcomp any_coup democracy_fh pol_rights civ_lib in_conflict intra_conflict country_risk dircredit creditceil creditcont ircontr entrybar banksup privat intcap secmarkets finreform unemployment_oecd econ_freedom cb_policy_rate corruption_gici approval_HOS approval_HOG appreciation trade_lib democracy_cgv democracy_bmr trade_g_gdpwb imp_g_gdpwb exp_g_gdpwb kofgi kofgi_econ kofgi_trade kofgi_fin kofgi_soc kofgi_interper kofgi_inform kofgi_culture kofgi_pol hhi_imports hhi_exports dem_anrr gini_inc_wid gini_wea_wid"
local winsorized_outcomes_list = "growth_gdpc_penn inflation_imf unemployment_ilo trade_wb growth_gdpc_madd growth_gdp_madd log_gdp_madd log_gdpc_madd growth_gdp_penn growth_cons_penn growth_cap_penn growth_prod_penn log_gdp_penn log_gdpc_penn appreciation trade_intensity imports_cepii exports_cepii imp_g_gdpwb exp_g_gdpwb trade_g_gdpwb growth_gdp_wb growth_gdpc_wb inflation_cp_wb inflation_def_wb imports_wb exports_wb cb_policy_rate cbi_cwn debt_imf exp_educ_gdp exp_gdp exp_health_gdp exp_mili_gdp share_educ_exp share_health_exp share_mili_exp share_tax_goods share_tax_income share_tax_trade subsidies_transf tax_revenue_wb tariff_wb log_gdp_wb log_gdpc_wb unemployment_oecd"

local outcomes_list_short = "growth_gdpc_penn inflation_imf unemployment_ilo trade_wb hdi lifeexp_index educ_index income_index democracy_index polyarchy liberal partip delib egal democracy_fh polity_score approval_HOS approval_HOG accountability ex_corruption pub_corruption control_corruption"
local winsorized_outcomes_list_short = "growth_gdpc_penn inflation_imf unemployment_ilo trade_wb"

////////////////////////////////////////////////////////////////////////////////
////	Regression datasets with one observation per election
////////////////////////////////////////////////////////////////////////////////

*** Program to build regression datasets 

capture program drop build_dataset
program define build_dataset
	
	args min_pre max_pre min_post max_post winsorize trim winsor_lowcut winsor_highcut exclude_inconsequential outcomes winsorized_outcomes output_file
	foreach arg in min_pre max_pre min_post max_post winsorize trim winsor_lowcut winsor_highcut exclude_inconsequential outcomes winsorized_outcomes output_file {
		dis "## `arg' = ``arg''"
	}

	use "$project_path/data/3_cleaned/outcomes", clear

	egen country_id = group(Country)
	xtset country_id Year

	// Building lagged variables
	foreach v in growth_gdpc_penn inflation_imf unemployment_ilo trade_wb hdi democracy_index cbi_cwn {
		gen lagged_`v' = L.`v'
		gen lagged2_`v' = L2.`v'
	}

	// We winsorize variables if necessary
	if `winsorize'==1 {
		if `trim'==1 local trim_option = "trim"
		if `trim'==0 local trim_option = ""
		foreach v in `winsorized_outcomes' {
			winsor2 `v', replace cuts(`winsor_lowcut' `winsor_highcut') `trim_option'
		}
	}

	** Building outcome variables
	foreach v in `outcomes' {
		dis "`v'"
		// We start by computing the forwards and lags of the outcome variables
		forvalues i=0/10 {
			qui gen `v'_`i'for = F`i'.`v'
		}
		forvalues i=1/10 {
			qui gen `v'_`i'lag = L`i'.`v'
		}
		// We find the variables which need to be aggregated in the pre- and post-election bins
		local pre_bin = ""
		local post_bin = ""
		forvalues i=`min_post'/`max_post' {
			local post_bin = "`post_bin' `v'_`i'for"
		}
		forvalues i=`min_pre'/`max_pre' {
			local pre_bin = "`pre_bin' `v'_`i'lag"
		}
		// We build transformed versions of variables
		qui egen pre_`v' = rowmean(`pre_bin')
		qui egen post_`v' = rowmean(`post_bin')
		qui gen diff_`v' = post_`v'-pre_`v'
		qui gen diff_m1_`v' = post_`v' - `v'_1lag
		qui gen adiff_m1_`v' = abs(post_`v' - `v'_1lag)
		// Standardizing variables
		foreach prefix in diff_ diff_m1_ adiff_m1_ {
			qui sum `prefix'`v' if election==1
			local temp_mean = r(mean)
			local temp_sd = r(sd)
			qui gen std_`prefix'`v' = (`prefix'`v'-`temp_mean')/`temp_sd'
		}
		drop pre_`v'  post_`v' `v'_*for 
		forvalues i = 4/10 {
			drop `v'_`i'lag
		}
	}

	** Building indices
	gen mstd_diff_m1_inflation_imf = -std_diff_m1_inflation_imf
	gen mstd_diff_m1_unemployment_ilo = -std_diff_m1_unemployment_ilo
	egen diff_m1_chix_econ = rowmean(std_diff_m1_growth_gdpc_penn mstd_diff_m1_inflation_imf mstd_diff_m1_unemployment_ilo std_diff_m1_trade_wb)
	sum diff_m1_chix_econ if election==1
	local temp_mean = r(mean)
	local temp_sd = r(sd)
	gen std_diff_m1_chix_econ = (diff_m1_chix_econ-`temp_mean')/`temp_sd'
	egen diff_m1_general_chix = rowmean(std_diff_m1_chix_econ std_diff_m1_hdi std_diff_m1_democracy_index)
	egen diff_m1_general_chix_nodem = rowmean(std_diff_m1_chix_econ std_diff_m1_hdi)
	
	** Indices using a 3 pre-election year average as baseline
	gen mstd_diff_inflation_imf = -std_diff_inflation_imf
	gen mstd_diff_unemployment_ilo = -std_diff_unemployment_ilo
	egen diff_chix_econ = rowmean(std_diff_growth_gdpc_penn mstd_diff_inflation_imf mstd_diff_unemployment_ilo std_diff_trade_wb)
	sum diff_chix_econ if election==1
	local temp_mean = r(mean)
	local temp_sd = r(sd)
	gen std_diff_chix_econ = (diff_m1_chix_econ-`temp_mean')/`temp_sd'
	egen diff_general_chix = rowmean(std_diff_chix_econ std_diff_hdi std_diff_democracy_index)	

	** Merge with running and treatment variables
	tempfile temp_outcomes
	save `temp_outcomes'
	use "$project_path/data/3_cleaned/turnovers_parliamentary_electoral", clear
	merge 1:1 Country Year Month Type_Election using "$project_path/data/3_cleaned/turnovers_parliamentary_executive", assert(master match) keepusing(runvar_alt treatment_alt incumbent_leader incumbent_leader_wid candidate_incumbency_wid) nogen
	append using "$project_path/data/3_cleaned/turnovers_presidential"
	merge m:1 Country Year using `temp_outcomes', assert(using match) keep(match) nogen

	** Subsamples

	// Full sample
	gen subsample_all = 1

	// Election type
	gen subsample_pres = 1 if Type_Election=="Presidential"
	gen subsample_parl = 1 if Type_Election=="Parliamentary"

	// OECD, regions
	merge m:1 Country using "$project_path/data/1_input/other/regions/regions", keep(match) assert(using match) nogen
	gen subsample_oecd = 1 if OECD==1
	gen subsample_not_oecd = 1 if OECD!=1
	gen subsample_asia 				= 1 if (Region=="Asia")
	gen subsample_asia_easteur 		= 1 if (Region=="Asia" | Region=="Eastern Europe")
	gen subsample_africa 			= 1 if (Region=="Africa")
	gen subsample_latin_america 	= 1 if (Region=="Latin America and Caribbean")
	gen subsample_east_europe 		= 1 if (Region=="Eastern Europe")
	gen subsample_oceania 			= 1 if (Region=="Oceania")
	gen subsample_west_oceania 		= 1 if (Region=="Oceania" | Region=="Western Europe and North America")
	gen subsample_west 				= 1 if (Region=="Western Europe and North America")

	// Pre vs. post-1990
	gen subsample_pre1990 = (Year<1990 & Year!=.)
	gen subsample_post1990 = (Year>=1990 & Year!=.)

	// Presidential and parliamentary regimes
	merge 1:1 Country Year Month Type_Election using "$project_path/data/2_intermediary/regimes/elections_regime_match", keepusing(regime) assert(using match) keep(match) nogen
	merge m:1 Country regime using "$project_path/data/3_cleaned/regimes", assert(using match) keep(match) keepusing(reg_type) nogen
	gen subsample_pres_regime = (reg_type=="Presidential")
	gen subsample_parl_regime = (reg_type=="Parliamentary")

	// Proportional vs. majoritarian parliamentary elections
	merge m:1 Country Year using "$project_path/data/2_intermediary/outcomes/outcomes_vdem.dta", keep(master match) keepusing(v2elparlel) nogen
	gen subsample_parlmaj = (Type_Election=="Parliamentary" & v2elparlel==0)
	gen subsample_parlprop = (Type_Election=="Parliamentary" & v2elparlel==1)

	// Democracies/autocracies -- xe use the Regimes of the world measure of V-Dem
	merge m:1 Country Year using "$project_path/data/2_intermediary/outcomes/outcomes_vdem.dta", keep(master match) keepusing(v2x_regime) nogen
	gen subsample_democ = 1 if v2x_regime==2 | v2x_regime==3
	gen subsample_autoc = 1 if v2x_regime==0 | v2x_regime==1

	// Incumbent leader on ballot/not on ballot
	gen subsample_incballot = 1 if incumbent_leader_wid==candidate_incumbency_wid & incumbent_leader_wid!="" & candidate_incumbency_wid!=""
	gen subsample_not_incballot = 1 if incumbent_leader_wid!=candidate_incumbency_wid & incumbent_leader_wid!="" & candidate_incumbency_wid!=""

	// Checks and balances
	merge m:1 Country Year using "$project_path/data/2_intermediary/outcomes/outcomes_vdem.dta", keep(master match) keepusing(lag_checks_balances_index) nogen
	sum lag_checks_balances_index if abs(runvar)<=15, d
	gen subsample_high_checks = 1 if lag_checks_balances_index!=. & lag_checks_balances_index>=r(p50)
	gen subsample_low_checks = 1 if lag_checks_balances_index!=. & lag_checks_balances_index<r(p50)

	// Leader power
	merge m:1 Country Year using "$project_path/data/2_intermediary/outcomes/outcomes_vdem.dta", keep(master match) keepusing(hos_power_linear hog_power_linear) nogen 
	merge 1:1 Country Year Month Type_Election using "$project_path/data/2_intermediary/leaders/elected_leaders.dta", assert(using match) keep(match) nogen
	gen power_index = .
	replace power_index = hos_power_linear if elected_leader=="HOS"
	replace power_index = hog_power_linear if elected_leader=="HOG"
	sum power_index if abs(runvar)<=15, d
	gen subsample_high_power = 1 if power_index!=. & power_index>=r(p50)
	gen subsample_low_power = 1 if power_index!=. & power_index<r(p50)

	// Globalization
	sum lagged_trade_wb if abs(runvar)<=15, d
	gen subsample_high_global = 1 if lagged_trade_wb!=. & lagged_trade_wb>=r(p50)
	gen subsample_low_global = 1 if lagged_trade_wb!=. & lagged_trade_wb<r(p50)

	// Term limit
	merge 1:1 Country Year Month Type_Election using "$project_path/data/2_intermediary/elections/Presidential elections/term_limits", assert(master match) nogen
	gen subsample_no_term_limit = 1 if (face_term_limit_incumbency==0 & face_term_limit_opposition==0) |  (face_term_limit_incumbency==1 & face_term_limit_opposition==1) | Type_Election=="Parliamentary"
	
	// Inflation
	sum lagged_inflation_imf if abs(runvar)<=15, d
	gen subsample_high_inflation = 1 if lagged_inflation_imf!=. & lagged_inflation_imf>=r(p50)
	gen subsample_low_inflation = 1 if lagged_inflation_imf!=. & lagged_inflation_imf<r(p50)

	// Unemployment
	sum lagged_unemployment_ilo if abs(runvar)<=15, d
	gen subsample_high_unemployment = 1 if lagged_unemployment_ilo!=. & lagged_unemployment_ilo>=r(p50)
	gen subsample_low_unemployment = 1 if lagged_unemployment_ilo!=. & lagged_unemployment_ilo<r(p50)

	// Central bank independence
	sum lagged_cbi_cwn if abs(runvar)<=15, d
	gen subsample_high_cbi = 1 if lagged_cbi_cwn!=. & lagged_cbi_cwn>=r(p50)
	gen subsample_low_cbi = 1 if lagged_cbi_cwn!=. & lagged_cbi_cwn<r(p50)

	// Major elections
	gen subsample_majorelec = 1 if (Type_Election=="Presidential" & reg_type=="Presidential") | (Type_Election=="Parliamentary" & reg_type=="Parliamentary")
	
	// Free and fair election
	merge m:1 Country Year using "$project_path/data/2_intermediary/outcomes/outcomes_vdem.dta", keep(master match) keepusing(election_freefair) nogen
	gen subsample_freefair = 1 if election_freefair==1
	gen subsample_not_freefair = 1 if election_freefair==0
	
	// Small and large parliament
	merge 1:1 Country Year Month Type_Election using "$project_path/data/3_cleaned/parliamentary_elections", keepusing(Total_Seats) keep(master match) nogen
	gen subsample_small_parl = 1 if Total_Seats<60 & Total_Seats!=. & Type_Election=="Parliamentary"
	gen subsample_large_parl = 1 if Total_Seats>=60 & Total_Seats!=. & Type_Election=="Parliamentary"
	drop Total_Seats
	
	// Time elapsed since last election
	sum elapsed_last_treatment, d
	gen subsample_elaps_last_treat_high = 1 if elapsed_last_treatment!=. & elapsed_last_treatment>=r(p50)
	gen subsample_elaps_last_treat_low = 1 if elapsed_last_treatment!=. & elapsed_last_treatment<r(p50)

	** Elections excluded from the sample
	drop if flag_not_last==1
	if `exclude_inconsequential'==1 drop if flag_inconsequential==1
	if `exclude_inconsequential'==1 drop if flag_coup==1

	** We set the running variable to missing when it's equal to 0 or -100 to exclude these elections from the RD estimation. We add flags to keep track of the change.
	gen flag_runvar_0 = 1 if runvar==0
	gen flag_runvar_m100 = 1 if runvar==-100
	gen flag_runvar_alt_0 = 1 if runvar_alt==0
	gen flag_runvar_alt_m100 = 1 if runvar_alt==-100
	replace runvar = . if runvar==0 | runvar==-100
	replace runvar_alt = . if runvar_alt==0 | runvar_alt==-100

	compress
	save "`output_file'", replace

end 

*** Main regression dataset
local min_pre = 1
local max_pre = 3
local min_post = 1
local max_post = 4
local winsorize = 1
local trim = 0
local winsor_lowcut = 3
local winsor_highcut = 97
local exclude_inconsequential = 1
local outcomes = "`outcomes_list'"
local winsorized_outcomes = "`winsorized_outcomes_list'"
local output_file = "$project_path/data/4_regdata/regdata"
build_dataset `min_pre' `max_pre' `min_post' `max_post' `winsorize' `trim' `winsor_lowcut' `winsor_highcut' `exclude_inconsequential' "`outcomes'" "`winsorized_outcomes'" "`output_file'"

*** Including inconsequential elections
local min_pre = 1
local max_pre = 3
local min_post = 1
local max_post = 4
local winsorize = 1
local trim = 0
local winsor_lowcut = 3
local winsor_highcut = 97
local exclude_inconsequential = 0
local outcomes = "`outcomes_list_short'"
local winsorized_outcomes = "`winsorized_outcomes_list_short'"
local output_file = "$project_path/data/4_regdata/robustness/regdata_with_inconsequential"
build_dataset `min_pre' `max_pre' `min_post' `max_post' `winsorize' `trim' `winsor_lowcut' `winsor_highcut' `exclude_inconsequential' "`outcomes'" "`winsorized_outcomes'" "`output_file'"

*** Trimming instead of winsorizing
local min_pre = 1
local max_pre = 3
local min_post = 1
local max_post = 4
local winsorize = 1
local trim = 1
local winsor_lowcut = 3
local winsor_highcut = 97
local exclude_inconsequential = 1
local outcomes = "`outcomes_list_short'"
local winsorized_outcomes = "`winsorized_outcomes_list_short'"
local output_file = "$project_path/data/4_regdata/robustness/regdata_trim"
build_dataset `min_pre' `max_pre' `min_post' `max_post' `winsorize' `trim' `winsor_lowcut' `winsor_highcut' `exclude_inconsequential' "`outcomes'" "`winsorized_outcomes'" "`output_file'"

*** Winsorizing at the 1st/99th percentiles
local min_pre = 1
local max_pre = 3
local min_post = 1
local max_post = 4
local winsorize = 1
local trim = 0
local winsor_lowcut = 1
local winsor_highcut = 99
local exclude_inconsequential = 1
local outcomes = "`outcomes_list_short'"
local winsorized_outcomes = "`winsorized_outcomes_list_short'"
local output_file = "$project_path/data/4_regdata/robustness/regdata_winsor_1_99"
build_dataset `min_pre' `max_pre' `min_post' `max_post' `winsorize' `trim' `winsor_lowcut' `winsor_highcut' `exclude_inconsequential' "`outcomes'" "`winsorized_outcomes'" "`output_file'"

*** Winsorizing at the 5th/95th percentiles
local min_pre = 1
local max_pre = 3
local min_post = 1
local max_post = 4
local winsorize = 1
local trim = 0
local winsor_lowcut = 5
local winsor_highcut = 95
local exclude_inconsequential = 1
local outcomes = "`outcomes_list_short'"
local winsorized_outcomes = "`winsorized_outcomes_list_short'"
local output_file = "$project_path/data/4_regdata/robustness/regdata_winsor_5_95"
build_dataset `min_pre' `max_pre' `min_post' `max_post' `winsorize' `trim' `winsor_lowcut' `winsor_highcut' `exclude_inconsequential' "`outcomes'" "`winsorized_outcomes'" "`output_file'"

*** 3 post-election years
local min_pre = 1
local max_pre = 3
local min_post = 1
local max_post = 3
local winsorize = 1
local trim = 0
local winsor_lowcut = 3
local winsor_highcut = 97
local exclude_inconsequential = 1
local outcomes = "`outcomes_list_short'"
local winsorized_outcomes = "`winsorized_outcomes_list_short'"
local output_file = "$project_path/data/4_regdata/robustness/regdata_3_post_years"
build_dataset `min_pre' `max_pre' `min_post' `max_post' `winsorize' `trim' `winsor_lowcut' `winsor_highcut' `exclude_inconsequential' "`outcomes'" "`winsorized_outcomes'" "`output_file'"

*** 5 post-election years
local min_pre = 1
local max_pre = 3
local min_post = 1
local max_post = 5
local winsorize = 1
local trim = 0
local winsor_lowcut = 3
local winsor_highcut = 97
local exclude_inconsequential = 1
local outcomes = "`outcomes_list_short'"
local winsorized_outcomes = "`winsorized_outcomes_list_short'"
local output_file = "$project_path/data/4_regdata/robustness/regdata_5_post_years"
build_dataset `min_pre' `max_pre' `min_post' `max_post' `winsorize' `trim' `winsor_lowcut' `winsor_highcut' `exclude_inconsequential' "`outcomes'" "`winsorized_outcomes'" "`output_file'"

*** 7 post-election years
local min_pre = 1
local max_pre = 3
local min_post = 1
local max_post = 7
local winsorize = 1
local trim = 0
local winsor_lowcut = 3
local winsor_highcut = 97
local exclude_inconsequential = 1
local outcomes = "`outcomes_list_short'"
local winsorized_outcomes = "`winsorized_outcomes_list_short'"
local output_file = "$project_path/data/4_regdata/robustness/regdata_7_post_years"
build_dataset `min_pre' `max_pre' `min_post' `max_post' `winsorize' `trim' `winsor_lowcut' `winsor_highcut' `exclude_inconsequential' "`outcomes'" "`winsorized_outcomes'" "`output_file'"

*** 10 post-election years
local min_pre = 1
local max_pre = 3
local min_post = 1
local max_post = 10
local winsorize = 1
local trim = 0
local winsor_lowcut = 3
local winsor_highcut = 97
local exclude_inconsequential = 1
local outcomes = "`outcomes_list_short'"
local winsorized_outcomes = "`winsorized_outcomes_list_short'"
local output_file = "$project_path/data/4_regdata/robustness/regdata_10_post_years"
build_dataset `min_pre' `max_pre' `min_post' `max_post' `winsorize' `trim' `winsor_lowcut' `winsor_highcut' `exclude_inconsequential' "`outcomes'" "`winsorized_outcomes'" "`output_file'"

*** With year 0 in the post period
local min_pre = 1
local max_pre = 3
local min_post = 0
local max_post = 4
local winsorize = 1
local trim = 0
local winsor_lowcut = 3
local winsor_highcut = 97
local exclude_inconsequential = 1
local outcomes = "`outcomes_list_short'"
local winsorized_outcomes = "`winsorized_outcomes_list_short'"
local output_file = "$project_path/data/4_regdata/robustness/regdata_with_year_0"
build_dataset `min_pre' `max_pre' `min_post' `max_post' `winsorize' `trim' `winsor_lowcut' `winsor_highcut' `exclude_inconsequential' "`outcomes'" "`winsorized_outcomes'" "`output_file'"

////////////////////////////////////////////////////////////////////////////////
////	Regression dataset for dynamic effects and placebo tests
////////////////////////////////////////////////////////////////////////////////

use "$project_path/data/3_cleaned/outcomes", clear
egen country_id = group(Country)
xtset country_id Year

// We winsorize variables
foreach v in `winsorized_outcomes_list_short' {
	winsor2 `v', replace cuts(3 97)
}

// Leads and lags of outcome variables
foreach v in `outcomes_list_short' {
	forvalues i=0/5 {
		qui gen `v'_`i'for = F`i'.`v'
	}
	forvalues i=1/4 {
		qui gen `v'_`i'lag = L`i'.`v'
	}
}

// We expand the dataset of outcomes for outcomes corresponding to relative years -4 to +5
expand(10)
bysort Country Year : gen relative_year = _n - 5

// We update outcome variables so that they match the relative year
foreach v in `outcomes_list_short' {
	forvalues i=1/4 {
		qui replace `v' = `v'_`i'lag if relative_year==-`i'
	}
	forvalues i=1/5 {
		qui replace `v' = `v'_`i'for if relative_year==`i'
	}
	// Difference with relative year -1
	qui gen diff_m1_`v' = `v' - `v'_1lag
	// We standardize outcomes using the same mean and standard deviations as in the main regression sample
	qui egen post_`v' = rowmean(`v'_1for `v'_2for `v'_3for `v'_4for)
	qui gen base_diff_m1_`v' = post_`v' - `v'_1lag
	qui sum base_diff_m1_`v' if election==1 & relative_year==0
	local temp_mean = r(mean)
	local temp_sd = r(sd)
	qui gen std_diff_m1_`v' = (diff_m1_`v'-`temp_mean')/`temp_sd'
	drop post_`v' base_diff_m1_`v'
}
drop *_*lag *_*for

// Building indices
gen mstd_diff_m1_inflation_imf = -std_diff_m1_inflation_imf
gen mstd_diff_m1_unemployment_ilo = -std_diff_m1_unemployment_ilo
egen diff_m1_chix_econ = rowmean(std_diff_m1_growth_gdpc_penn mstd_diff_m1_inflation_imf mstd_diff_m1_unemployment_ilo std_diff_m1_trade_wb)
sum diff_m1_chix_econ if election==1
local temp_mean = r(mean)
local temp_sd = r(sd)
gen std_diff_m1_chix_econ = (diff_m1_chix_econ-`temp_mean')/`temp_sd'
egen diff_m1_general_chix = rowmean(std_diff_m1_chix_econ std_diff_m1_hdi std_diff_m1_democracy_index)

// Merge with running and treatment variables
tempfile outcomes
save `outcomes'
use "$project_path/data/3_cleaned/turnovers_parliamentary_electoral", clear
merge 1:1 Country Year Month Type_Election using "$project_path/data/3_cleaned/turnovers_parliamentary_executive", assert(master match) keepusing(runvar_alt treatment_alt) nogen
append using "$project_path/data/3_cleaned/turnovers_presidential"
expand(10)
bysort Country Year Month Type_Election : gen relative_year = _n - 5
order Country Year Month Type_Election relative_year
merge m:1 Country Year relative_year using `outcomes', assert(using match) keep(match) nogen

// Elections excluded from the sample
drop if flag_not_last==1
drop if flag_inconsequential==1
drop if flag_coup==1

// Elected leaders
merge m:1 Country Year Month Type_Election using "$project_path/data/4_regdata/regdata", assert(match) keepusing(elected_leader) nogen

// We set the running variable to missing when it's equal to 0 or -100 to exclude these elections from the RD estimation. We add flags to keep track of the change.
gen flag_runvar_0 = 1 if runvar==0
gen flag_runvar_m100 = 1 if runvar==-100
gen flag_runvar_alt_0 = 1 if runvar_alt==0
gen flag_runvar_alt_m100 = 1 if runvar_alt==-100
replace runvar = . if runvar==0 | runvar==-100
replace runvar_alt = . if runvar_alt==0 | runvar_alt==-100

sort Country Year Month Type_Election relative_year

compress
save "$project_path/data/4_regdata/dynamics/regdata_dynamics", replace

